package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.Control.*;
import com.ruoyi.system.domain.QService;
import com.ruoyi.system.domain.SysMedical;
import com.ruoyi.system.service.IQServiceService;
import com.ruoyi.web.controller.common.Tdata1;
import com.ruoyi.web.controller.common.TelRecord;
import okhttp3.*;
import okhttp3.RequestBody;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import cn.hutool.core.date.DateUtil;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    private String prefix = "system/dept";

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IQServiceService iqServiceService;

    @RequiresPermissions("system:dept:view")
    @GetMapping()
    public String dept() {
        return prefix + "/dept";
    }

    @RequiresPermissions("system:dept:list")
    @PostMapping("/list")
    @ResponseBody
    public List<SysDept> list(SysDept dept) {
        List<SysDept> deptList = deptService.selectDeptList(dept);
        return deptList;
    }


    @PostMapping("/openapi/getLaomorData")
    @ResponseBody
    public List<SysMedical> getMedicalData() {
        List<SysMedical> medicalList = deptService.selectZhonggongMedicalData();
        return medicalList;
    }

    public String gettoken() throws IOException {


        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(99999, TimeUnit.SECONDS) //连接超时
                .readTimeout(99999, TimeUnit.SECONDS) //读取超时
                .writeTimeout(99999, TimeUnit.SECONDS) //写超时
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "{\r\n    \"appid\": \"canv\",\r\n    \"appsecret\": \"dky@2021Admin\"\r\n}");
        Request request = new Request.Builder()
                .url("http://111.22.175.38:10081/admin/api/openlogin.php")
                .method("POST", body)
                .addHeader("token", "eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiIxIiwibmFtZSI6ImFkbWluIiwiaXAiOiIxNzIuMzEuMTI1LjM4IiwidWEiOiIzNzJkOCIsIm9nIjoiMSIsImlhdCI6MTcwNDk0MTk4M30.mrjOeSjNwsw6p9PIL-okqaWKY5GVgy0XwTbfgZUxq5lD0xi53UIbthw6xM6IFz2ERkbNhQSELkOZfZ4DHmcMYA")
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiIxIiwibmFtZSI6ImFkbWluIiwiaXAiOiIxNzIuMzEuMTI1LjM4IiwidWEiOiIzNzJkOCIsIm9nIjoiMSIsImlhdCI6MTcwNDk0MTk4M30.mrjOeSjNwsw6p9PIL-okqaWKY5GVgy0XwTbfgZUxq5lD0xi53UIbthw6xM6IFz2ERkbNhQSELkOZfZ4DHmcMYA")
                .addHeader("Accept", "*/*")
                .addHeader("Host", "111.23.145.33:20001")
                .addHeader("Connection", "keep-alive")
                .build();
        Response response = client.newCall(request).execute();

        // 输出响应内容
        String str = (response.body().string());
        //第一种方式
        Map maps = (Map) JSON.parse(str);
        System.out.println("这个是用JSON类来解析JSON字符串!!!");

        for (Object map : maps.entrySet()) {
            if (((Map.Entry) map).getKey().equals("data")) {
                // System.out.println(((Map.Entry)map).getKey()+"     " + ((Map.Entry)map).getValue());
                String json = ((Map.Entry) map).getValue().toString();

                Map token = (Map) JSON.parse(json);

                for (Object map1 : token.entrySet()) {
                    if (((Map.Entry) map1).getKey().equals("x-token")) {
                        return ((Map.Entry<String, String>) map1).getValue();

                    }

                }


            }


        }
        return "123";
    }


    @PostMapping("/openapi/getCanvData")
    @ResponseBody
    public List<Tdata1> getCanvData(@org.springframework.web.bind.annotation.RequestBody TimeRec timeRec) throws IOException {
        System.out.println("获取数据开始：");

        String xtoken = gettoken() ;
        System.out.println("获取数据开始：" + xtoken);

        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(99999, TimeUnit.SECONDS) //连接超时
                .readTimeout(99999, TimeUnit.SECONDS) //读取超时
                .writeTimeout(99999, TimeUnit.SECONDS) //写超时
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "{ \"page\":1,   \"perNum\":50000,  \r\n    \"begintime\": \""+ timeRec.getBegintime() +"\",\r\n     \"endtime\": \""+ timeRec.getEndtime() +"\"\r\n}");
        Request request = new Request.Builder()
                .url("http://111.22.175.38:10081/admin/api/syscdrlist.php")
                .method("POST", body)
                .addHeader("x-token", xtoken)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")

                .addHeader("Accept", "*/*")
                .addHeader("Host", "111.23.145.33:20001")
                .addHeader("Connection", "keep-alive")
                .build();
        Response response = client.newCall(request).execute();

        // 输出响应内容
        String str = (response.body().string());
        //第一种方式
        Map maps = (Map) JSON.parse(str);
        System.out.println("这个是用JSON类来解析JSON字符串!!!");
        List<ghEnt> listgh = new ArrayList<ghEnt>();
        for (Object map : maps.entrySet()) {
            if (((Map.Entry) map).getKey().equals("data")) {
                System.out.println(((Map.Entry) map).getKey() + "     " + ((Map.Entry) map).getValue());
                String json = ((Map.Entry) map).getValue().toString();

                ObjectMapper objectMapper = new ObjectMapper();
                TypeReference<TelRecord> typeRef = new TypeReference<TelRecord>() {
                };
                TelRecord telRecord = objectMapper.readValue(json, typeRef);

                List<Tdata1> items = new ArrayList<Tdata1>();
                items = telRecord.getItems();
                System.out.println(items.size());
                for (int i = 0; i < items.size(); i++) {

                    Tdata1 cbkTelRecord = new Tdata1();
                    cbkTelRecord = items.get(i);
                    //保存服务回话到q_server
                    QService qService = new QService();
                    qService.setServiceId(cbkTelRecord.getLinkedid());
                    qService.setServicetype("5");  //通话记录
                    qService.setBeginTime(cbkTelRecord.getBegintime());
                    qService.setEndTime(cbkTelRecord.getEndtime());
                    // qService.setCause(String.valueOf(cbkTelRecord.getCause()));
                    qService.setWaittime(cbkTelRecord.getAnsweredtime());

                    qService.setCallernum(cbkTelRecord.getLocalnumber());
                    qService.setFromnum(cbkTelRecord.getCallerid());
                    qService.setSatisfaction(cbkTelRecord.getEvaluation());

                    System.out.println("=============================:" + cbkTelRecord.getExtension());
                    if (cbkTelRecord.getExtension() != null && !cbkTelRecord.getExtension().equals("") && cbkTelRecord.getExtension().length() > 4) {
                        cbkTelRecord.setExtension(cbkTelRecord.getCallerid());

                    } else {
                        ;

                    }
                    qService.setAgentid(String.valueOf(10000 + Integer.valueOf((cbkTelRecord.getExtension() == null || cbkTelRecord.getExtension().equals("")) ? ("0") : (cbkTelRecord.getExtension()))));//前缀少1
                    if (cbkTelRecord.getDirection().equals("out")) {
                        qService.setIsinside("3");
                    }
                    if (cbkTelRecord.getDirection().equals("in")) {
                        qService.setIsinside("2");
                    }
                    if (cbkTelRecord.getHasanswered().equals("0")) {
                        qService.setState("5");
                    }
                    if (cbkTelRecord.getHasanswered().equals("1")) {
                        qService.setState("3");
                    }

                    //满意度
                    if (cbkTelRecord.getEvaluation().equals("1")) { //满意
                        qService.setSatisfaction("2");
                    }
                    if (cbkTelRecord.getEvaluation().equals("2")) { //一般
                        qService.setSatisfaction("3");
                    }
                    if (cbkTelRecord.getEvaluation().equals("3")) {  //不满意
                        qService.setSatisfaction("5");
                    }


                    if (iqServiceService.selectQServiceByServiceId(cbkTelRecord.getLinkedid()) == null) {
                        iqServiceService.insertQService(qService);
                    } else {
                        iqServiceService.updateQService(qService);
                    }

                }
                return items;
            }

        }

        return null;

    }

    @PostMapping("/openapi/getXtoken")
    @CrossOrigin
    @ResponseBody
    public String getXtoken() throws IOException {


        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(99999, TimeUnit.SECONDS) //连接超时
                .readTimeout(99999, TimeUnit.SECONDS) //读取超时
                .writeTimeout(99999, TimeUnit.SECONDS) //写超时
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "{\r\n    \"appid\": \"canv\",\r\n    \"appsecret\": \"dky@2021Admin\"\r\n}");
        Request request = new Request.Builder()
                .url("http://111.22.175.38:10081/admin/api/openlogin.php")
                .method("POST", body)
                .addHeader("token", "eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiIxIiwibmFtZSI6ImFkbWluIiwiaXAiOiIxNzIuMzEuMTI1LjM4IiwidWEiOiIzNzJkOCIsIm9nIjoiMSIsImlhdCI6MTcwNDk0MTk4M30.mrjOeSjNwsw6p9PIL-okqaWKY5GVgy0XwTbfgZUxq5lD0xi53UIbthw6xM6IFz2ERkbNhQSELkOZfZ4DHmcMYA")
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiIxIiwibmFtZSI6ImFkbWluIiwiaXAiOiIxNzIuMzEuMTI1LjM4IiwidWEiOiIzNzJkOCIsIm9nIjoiMSIsImlhdCI6MTcwNDk0MTk4M30.mrjOeSjNwsw6p9PIL-okqaWKY5GVgy0XwTbfgZUxq5lD0xi53UIbthw6xM6IFz2ERkbNhQSELkOZfZ4DHmcMYA")
                .addHeader("Accept", "*/*")
                .addHeader("Host", "111.23.145.33:20001")
                .addHeader("Connection", "keep-alive")
                .build();
        Response response = client.newCall(request).execute();

        // 输出响应内容
        String str = (response.body().string());
        //第一种方式
        Map maps = (Map) JSON.parse(str);
        System.out.println("这个是用JSON类来解析JSON字符串!!!");

        for (Object map : maps.entrySet()) {
            if (((Map.Entry) map).getKey().equals("data")) {
                // System.out.println(((Map.Entry)map).getKey()+"     " + ((Map.Entry)map).getValue());
                String json = ((Map.Entry) map).getValue().toString();

                Map token = (Map) JSON.parse(json);

                for (Object map1 : token.entrySet()) {
                    if (((Map.Entry) map1).getKey().equals("x-token")) {
                        return ((Map.Entry<String, String>) map1).getValue();

                    }

                }


            }


        }
        return "123";
    }


    /**
     * 新增部门
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) {
        if (!getSysUser().isAdmin()) {
            parentId = getSysUser().getDeptId();
        }
        mmap.put("dept", deptService.selectDeptById(parentId));
        return prefix + "/add";
    }

    /**
     * 新增保存部门
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:dept:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getLoginName());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit")
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) {
        deptService.checkDeptDataScope(deptId);
        SysDept dept = deptService.selectDeptById(deptId);
        if (StringUtils.isNotNull(dept) && 100L == deptId) {
            dept.setParentName("无");
        }
        mmap.put("dept", dept);
        return prefix + "/edit";
    }

    /**
     * 修改保存部门
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:dept:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getLoginName());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:dept:remove")
    @GetMapping("/remove/{deptId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("deptId") Long deptId) {
        if (deptService.selectDeptCount(deptId) > 0) {
            return AjaxResult.warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public boolean checkDeptNameUnique(SysDept dept) {
        return deptService.checkDeptNameUnique(dept);
    }

    /**
     * 选择部门树
     *
     * @param deptId    部门ID
     * @param excludeId 排除ID
     */
    @GetMapping(value = {"/selectDeptTree/{deptId}", "/selectDeptTree/{deptId}/{excludeId}"})
    public String selectDeptTree(@PathVariable("deptId") Long deptId,
                                 @PathVariable(value = "excludeId", required = false) Long excludeId, ModelMap mmap) {
        mmap.put("dept", deptService.selectDeptById(deptId));
        mmap.put("excludeId", excludeId);
        return prefix + "/tree";
    }

    /**
     * 加载部门列表树（排除下级）
     */
    @GetMapping("/treeData/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) Long excludeId) {
        SysDept dept = new SysDept();
        dept.setExcludeId(excludeId);
        List<Ztree> ztrees = deptService.selectDeptTreeExcludeChild(dept);
        return ztrees;
    }
}
